<?php

namespace App\Http\Middleware;
use App\Models\User;
use Closure;

class TransferSession{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        $wechat_user = session('wechat.oauth_user.default');
        $wechat_info = $wechat_user->original;
        $user_info = session('user_info_'.$wechat_info['openid'],[]);
        if(empty($user_info)){
            $user = User::where('openid',$wechat_info['openid'])->first();
            if(is_null($user)){
                $wechat_info = $wechat_user->original;
                $user = new User;
                $user->openid = $wechat_info['openid'];
                $user->nickname = $wechat_info['nickname'];
                $user->sex = $wechat_info['sex'];
                $user->city = $wechat_info['city'];
                $user->province = $wechat_info['province'];
                $user->country = $wechat_info['country'];
                $user->avatar = $wechat_info['headimgurl'];
                $user->password = bcrypt('weierban123456');
                # 获取url 中的weixin_id
                $match = [];
                $url = $request->url();
                preg_match('/\w+([1-9]\d*)/',$url,$match);
                $user->weixin_id = $match[1] ?? 0;
                $user->recommend_id = 0;
                // access_token + openid 获取用户信息，判断是否关注公众号
                $app = app('wechat.official_account');
                $weixin_userinfo = $app->user->get($wechat_info['openid']);
                $user->subscribe = $weixin_userinfo['subscribe'] ?? 0;
                $user->save();
            }
            session(['user_info_'.$wechat_info['openid'] => $user]);
        }
        return $next($request);
    }
}